//
//  YFMapLocationVC.m
//  QuanJieShopProject
//
//  Created by apple on 2018/4/17.
//  Copyright © 2018年 apple. All rights reserved.
//

#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件
#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引入检索功能所有的头文件
#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>//引入云检索功能所有的头文件
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>//引入计算工具所有的头文件
#import <BaiduMapAPI_Radar/BMKRadarComponent.h>//引入周边雷达功能所有的头文件
#import <BaiduMapAPI_Map/BMKMapView.h>//只引入所需的单个头文件

#define CellIdntifier @"placeInfoCellIdentifier"

#import "YFMapLocationVC.h"
#import "QJLocationInfoCell.h"
#import "QJLocationInfoModel.h"

@interface YFMapLocationVC ()<BMKMapViewDelegate,BMKLocationServiceDelegate,UITableViewDelegate,UITableViewDataSource,BMKPoiSearchDelegate>
{
    BOOL _isFirstLocation; // 是否是第一次定位
    NSMutableArray *infoArray;//周围信息
    QJLocationInfoModel *_selectModel;
}
@property (nonatomic, strong) BMKMapView *mapView;
@property (nonatomic, strong) BMKLocationService *locService;
@property (nonatomic, strong) BMKPoiSearch *poiSearch;
@property (nonatomic, strong) BMKGeoCodeSearch *geoCodeSearch;

@property (nonatomic, strong) UIImageView *middleLocationImgView;
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSString *address;

@property (nonatomic, assign) CLLocationCoordinate2D userLocation;
@property (nonatomic, assign) CLLocationCoordinate2D middleLocation;
@end

@implementation YFMapLocationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _isFirstLocation = YES;
    infoArray = [NSMutableArray array];
    self.address = @"";
    
//    CGFloat top = IS_iOS11Later ? Height_NavBar : 0;

    // 创建地图
    BMKMapView* mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, UISCREEN_WIDTH, UISCREEN_HEIGHT )];
    [self.view addSubview:mapView];
    mapView.delegate = self;
    mapView.showsUserLocation = NO;//先关闭显示的定位图层
    mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    mapView.showsUserLocation = YES;//显示定位图层
    self.mapView = mapView;
    
    // 定位
    _locService = [[BMKLocationService alloc]init];
    [_locService startUserLocationService];
    
    // poi初始化检索对象
    _poiSearch =[[BMKPoiSearch alloc]init];
    
    //
    _geoCodeSearch = [[BMKGeoCodeSearch alloc] init];
    
    //右侧按钮
    UIButton *rightButton = [[UIButton alloc] init];
    [rightButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [rightButton sizeToFit];
    [rightButton setTitle:@"完成" forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    [rightButton addTarget:self action:@selector(rightItemClicked) forControlEvents:UIControlEventTouchUpInside];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.middleLocationImgView;// 懒加载

    
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _locService.delegate = self;
    _poiSearch.delegate = self;
    _geoCodeSearch.delegate = self;
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _locService.delegate = nil;
    _poiSearch.delegate = nil;
    _geoCodeSearch.delegate = nil;
    
    // 开启返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    // 禁用返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}


#pragma mark - 百度地图相关
/**
 *在地图View将要启动定位时，会调用此函数
 *@param mapView 地图View
 */
- (void)willStartLocatingUser
{
    KMyLog(@"start locate");
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    
    [_mapView updateLocationData:userLocation];
//    KMyLog(@"heading is %@",userLocation.heading);
}
/**
 *定位失败后，会调用此函数
 *@param error 错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error {
    
//    KMyLog(@"定位失败了");
    [MBPHUD showAlertWithTitle:@"定位失败, 请确认手机已联网并开启定位, 然后重试!"];
}
/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
//    KMyLog(@"latitude = %f, longitude = %f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
    // 不用 _isFirstLocation 或者定位到数据就停止定位
    if (userLocation.location.coordinate.latitude != 0 && userLocation.location.coordinate.longitude != 0 && _isFirstLocation) {
        _isFirstLocation = NO;
        // 设置地图区域
        BMKCoordinateSpan span = BMKCoordinateSpanMake(0.013142, 0.011678);
    
        self.userLocation = userLocation.location.coordinate;
        self.middleLocation = userLocation.location.coordinate;
        
        _mapView.region = BMKCoordinateRegionMake(self.userLocation, span);
        
//        [self startPoiSearch];
        [self startGeoCodeSearch];
    }
    [_mapView updateLocationData:userLocation];
}

/**
 *地图区域改变完成后会调用此接口
 *@param mapview 地图View
 *@param animated 是否动画
 */
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    KMyLog(@"zoom level: %lf", mapView.zoomLevel);
    
    // 中心点坐标
    KMyLog(@"latitude = %f, longitude = %f", mapView.centerCoordinate.latitude, mapView.centerCoordinate.longitude);
    
    self.middleLocation = mapView.centerCoordinate;
    
//    [self startPoiSearch];
    [self startGeoCodeSearch];
}


/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser
{
    KMyLog(@"stop locate");
}


#pragma mark - poi
//实现PoiSearchDeleage处理回调结果
- (void)onGetPoiResult:(BMKPoiSearch*)searcher result:(BMKPoiResult*)poiResultList errorCode:(BMKSearchErrorCode)error
{
    // POI列表，成员是BMKPoiInfo
    KMyLog(@"poiResultList = %@", poiResultList);
    KMyLog(@"totalPoiNum = %d", poiResultList.totalPoiNum);
    for (BMKPoiInfo *info in poiResultList.poiInfoList) {
        KMyLog(@"name= %@, add = %@", info.name, info.address);
    }

    if (error == BMK_SEARCH_NO_ERROR) {
        //在此处理正常结果
    }
    else if (error == BMK_SEARCH_AMBIGUOUS_KEYWORD){
        //当在设置城市未找到结果，但在其他城市找到结果时，回调建议检索城市列表
        // result.cityList;
        KMyLog(@"起始点有歧义");
    } else {
        KMyLog(@"抱歉，未找到结果");
    }
}

#pragma mark - geoCode
//接收反向地理编码结果
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:
(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        KMyLog(@"result = %@", result.address);
        self.address = result.address;
        
        /*
         //具体位置
         @property (nonatomic, strong) NSString *name;
         //街道
         @property (nonatomic, strong) NSString *thoroughfare;
         //子街道
         @property (nonatomic, strong) NSString *subThoroughfare;
         //市
         @property (nonatomic, strong) NSString *city;
         //经纬度
         @property (nonatomic) CLLocationCoordinate2D coordinate;
         */
        _selectModel = [[QJLocationInfoModel alloc] init];
        _selectModel.name = result.address;
        _selectModel.coordinate = result.location;
    }
    else {
        self.address = @"";
        KMyLog(@"抱歉，未找到结果");
    }
}

#pragma mark - #pragma mark - UITableViewDelegate & UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return infoArray.count;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    QJLocationInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdntifier forIndexPath:indexPath];
    QJLocationInfoModel *model = [infoArray objectAtIndex:indexPath.row];
    cell.titleLabel.text = model.name;
    cell.subTitleLabel.text = model.thoroughfare;
    return cell;
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    QJLocationInfoModel *model = [infoArray objectAtIndex:indexPath.row];
    _selectModel = model;
}

#pragma mark - 私有方法
- (void)startGeoCodeSearch {
    
    //发起反向地理编码检索
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    KMyLog(@"反geo latitude =%f, longitude = %f", self.middleLocation.latitude, self.middleLocation.longitude);
    reverseGeoCodeSearchOption.reverseGeoPoint = self.middleLocation;
    BOOL flag = [_geoCodeSearch reverseGeoCode:reverseGeoCodeSearchOption];
    if(flag)
    {
        KMyLog(@"反geo检索发送成功");
    }
    else
    {
        KMyLog(@"反geo检索发送失败");
        // 说明有位置信息, 但是检索失败
        if (self.userLocation.latitude != 0 && self.userLocation.longitude != 0) {
            [self startGeoCodeSearch];
        }
    }
}

- (void)startPoiSearch {   // 不需要poi了, 地图只是为了获取经纬度
    
    //发起检索
    BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc]init];
    //    option.pageIndex = curPage;
    option.pageCapacity = 10;
    option.location = self.middleLocation;
    option.keyword = @"小吃,酒店";
    BOOL flag = [_poiSearch poiSearchNearBy:option];
    if(flag)
    {
        KMyLog(@"周边检索发送成功");
    }
    else
    {
        KMyLog(@"周边检索发送失败");
    }
}

- (void)rightItemClicked{
    
    if (self.address.length != 0) {
        if (self.locationAddressBlock) {
            self.locationAddressBlock(_selectModel);
            KPopViewControllerAction;
        }
    }else{
        [MBPHUD showAlertWithTitle:@"位置检索失败, 请确认开启定位, 然后重试!"];
    }
}

#pragma mark - 懒加载
- (UIImageView *)middleLocationImgView {
    if (!_middleLocationImgView) {
        UIImageView *imgView = [[UIImageView alloc] init];
        imgView.image = [UIImage imageNamed:@"pin_red"];
//        CGPoint middlePoint = [self.mapView convertPoint:self.mapView.center toView:self.view];  // 转换的中心点偏了
        CGFloat imgWH = 30;
        imgView.frame = CGRectMake(self.mapView.mj_w/2.f - imgWH/2, self.mapView.mj_y + self.mapView.mj_h/2.f - imgWH/2, imgWH, imgWH);
        [self.view addSubview:imgView];
//        imgView.backgroundColor = [UIColor blueColor];
        _middleLocationImgView = imgView;
    }
    return _middleLocationImgView;
}

//- (UITableView *)tableView {
//    if (!_tableView) {
//        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.mapView.frame), UISCREEN_WIDTH, UISCREEN_HEIGHT - CGRectGetMaxY(self.mapView.frame))];
//        tableView.delegate = self;
//        tableView.dataSource = self;
//        [self.view addSubview:tableView];
//        tableView.backgroundColor = [UIColor blueColor];
//        _tableView = tableView;
//    }
//    return _tableView;
//}

@end
